package com.linxi.rpccompensation.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linxi.rpccompensation.annotation.Compensation;
import com.linxi.rpccompensation.constant.Constant;
import com.linxi.rpccompensation.entity.SysPushLog;
import com.linxi.rpccompensation.mapper.PushLogMapper;
import com.linxi.rpccompensation.service.PushLogService;
import com.linxi.rpccompensation.util.HttpUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @description: 日志推送service，对内细节封装
 * @author：lx
 * @date: 2021/09/26 下午 9:41
 * @Copyright： lx
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PushLogServiceImpl extends ServiceImpl<PushLogMapper, SysPushLog> implements PushLogService {

	@Resource
	private HttpUtil httpUtil;

	@Override
	public String savePushLog(String api, String data) {
		SysPushLog pushLog = new SysPushLog();
		String id = IdUtil.randomUUID();
		pushLog.setId(id);
		pushLog.setApi(api);
		pushLog.setData(data);
		pushLog.setTime(new Date());
		pushLog.setStatus(1);
		save(pushLog);
		return id;
	}

	@Override
	public void updateSuccess(String id) {
		SysPushLog pushLog = getById(id);
		if (pushLog != null) {
			pushLog.setStatus(3);
			updateById(pushLog);
		}
	}

	@Override
	public void updateFail(String id) {
		SysPushLog pushLog = getById(id);
		if (pushLog != null) {
			pushLog.setStatus(2);
			updateById(pushLog);
		}
	}

	@Override
	@Compensation(api = Constant.PUSH_TASK)
	public void doPushTask(SysPushLog pushLog) throws Exception {
		httpUtil.doPush(Constant.PUSH_TASK, pushLog);
	}

	@Override
	@Compensation()
	public boolean doPush(String api, String pushLog) throws Exception {
		return httpUtil.doPushByJson(api, pushLog);
	}
}
